import sys
import os
import re
import markdown

umlCount = 0
workspace = os.path.dirname(sys.argv[2])
umlNameBase = os.path.basename(sys.argv[2])

def GenerateUML(umlLines, tag):
    global umlCount
    umlCount += 1
    umlTempFile = sys.argv[2] + ".uml." + tag + ".{0}.tmp".format(umlCount)
    with open(umlTempFile, "w") as f:
        f.write(umlLines)
    if os.path.exists(umlTempFile):
        os.system("plantuml -tsvg -o {0} {1}".format(workspace, umlTempFile))
        os.system("rm " + umlTempFile)
        if os.path.exists(sys.argv[2] + ".uml." + tag + ".{0}.svg".format(umlCount)):
            formatStr = "![uml." + tag + ".{0}]({1}.uml." + tag + ".{2}.svg)"
            umlImageLine = formatStr.format(umlCount, umlNameBase, umlCount)
            return umlImageLine
    return "![uml." + tag + ".{0}]()".format(umlCount)

def GetUmlTag(line):
    tags = ("uml", "regex", "salt", "gantt", "chronology", "mindmap", "wbs", "ebnf", "json", "yaml")
    for tag in tags:
        if re.match("^@start" + tag + "*", line):
            return tag
    return ""

def IsUmlEnd(line, tag):
    return re.match("^@end" + tag + "*", line)

if __name__ == "__main__":
    try:
        with open(sys.argv[1]) as fIn:
            contents = ""
            uml = ""
            isUMLLine = False
            currentTag = ""
            for line in fIn.readlines():
                if isUMLLine:
                    if IsUmlEnd(line, currentTag):
                        contents += GenerateUML(uml + line, currentTag)
                        isUMLLine = False
                        currentTag = ""
                    else:
                        uml += line
                else:
                    tag = GetUmlTag(line)
                    if tag:
                        isUMLLine = True
                        currentTag = tag
                        uml = line
                    else:
                        contents += line
            if isUMLLine:
                raise Exception("UML tags are not match! Tag = " + currentTag)
            output = markdown.markdown(contents, extensions=['markdown.extensions.tables', 'markdown.extensions.fenced_code'])
            with open(sys.argv[2], "w") as fOut:
                fOut.write(output)
    except Exception as e:
        with open(sys.argv[3], "w") as fErr:
            fErr.write(str(e))

        
        
